package climspace.ejb;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import climspace.hadoop.ArchiveStation;
import climspace.hadoop.ArchiveStationImpl;

@MessageDriven(activationConfig = {
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/climspace/rdbms"),
		@ActivationConfigProperty(propertyName = "maxSession", propertyValue = "10") })
public class UploadStationMDB implements MessageListener {

	@PersistenceContext(unitName = "persistenceRDBMS")
	private EntityManager data;

	@Override
	public void onMessage(Message message) {
		try {
			MapMessage mapMessage = (MapMessage) message;
			String fileName = mapMessage.getString("fileName");
			String fileType = mapMessage.getString("fileType");
			parseFile(fileName, fileType);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	private void parseFile(String fileName, String fileType) {
		FileParser fileparser = new FileParser();
		fileparser.setData(data);
		
		Long start = System.currentTimeMillis();
		Long end = start;
		
		if (Constants.WEATHER_STATION_FILE.equals(fileType)) {
			fileparser.parseWeatherStationFile(fileName);
			end = System.currentTimeMillis();
			System.out.println("station cvs parse time (ms): " + (end-start));
			start = end;
		} else if (Constants.WEATHER_DATA_FILE.equals(fileType)) {
			fileparser.parseWeatherDataFile(fileName);
			end = System.currentTimeMillis();
			System.out.println("station data parse time (ms): " + (end-start));
			start = end;
			// TODO ArchiveStation with default configurations
			ArchiveStation archiveStation = new ArchiveStationImpl();
			archiveStation.uploadDataFile(fileName);
			end = System.currentTimeMillis();
			System.out.println("station data upload to hdfs time (ms): " + (end-start));
			start = end;
		} else {
			System.out.println("************** File Type Not supported!");
		}
	}
}
